package com.cloud_notes.demo.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtil {
    //自定义秘钥
    private static final String secret ="qwertyuioplkjhgfdsazxcvbnmmmmmmllllpoiuytrewsdf";
    //根据自定义生成安全的密钥
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));
    //密钥过期时间
    public static long expiration = 24*60*60*1000;//⼀天

    //生成
    public static String genJwt(Map<String, Object> claim){
        //签名算法
        String jwt = Jwts.builder()
                .setClaims(claim) //⾃定义内容(载荷)
                .setIssuedAt(new Date())// 设置签发时间
                .setExpiration(new Date(System.currentTimeMillis() +
                        expiration)) //设置过期时间
                .signWith(key) //签名算法
                .compact();
        return jwt;
    }

    //验证
    public static Claims parseJWT(String jwt){
        if (!StringUtils.hasLength(jwt)){
            return null;
        }
        //创建解析器, 设置签名密钥
        JwtParserBuilder jwtParserBuilder =
                Jwts.parserBuilder().setSigningKey(key);
        Claims claims = null;
        try {
            //解析token
            claims = jwtParserBuilder.build().parseClaimsJws(jwt).getBody();
        }catch (Exception e){
            //签名验证失败
            log.error("解析令牌错误,jwt:{}",jwt);
        }
        return claims;
    }
}
